package com.awx.client.login;

import java.awt.Dimension;
import java.awt.Toolkit;

import javax.swing.JFrame;
import javax.swing.SwingUtilities;
import javax.swing.UIManager;
import javax.swing.UnsupportedLookAndFeelException;

import com.awx.client.exception.AwxClientException;
import com.awx.client.navigation.AwxApplication;
import com.awx.client.navigation.menu.AwxMenuConfiguration;
import com.awx.client.rpc.AwxRpc;
import com.sun.java.swing.plaf.windows.WindowsLookAndFeel;

public class AwxLoginWindow extends JFrame {

	public static final String DEFAULT_LOGIN_SERVER = "defaultLoginServer";


	private AwxLoginUser loginUser;
	private AwxApplication application;
	private AwxMenuConfiguration menuConfiguration;


	public AwxLoginWindow() {
		this.setVisible( false );
		this.setDefaultCloseOperation( DISPOSE_ON_CLOSE );
		this.configureAppereance();
		this.loginUser = new AwxLoginUser();
	}

	private void configureAppereance() {
		try {
    		UIManager.setLookAndFeel( new WindowsLookAndFeel() );
    	} catch (UnsupportedLookAndFeelException ex) {
    		throw new AwxClientException( "Error stting XP look and feel", ex );
    	}
    	SwingUtilities.updateComponentTreeUI( this );
	}


	private void centerWindow() {
		Dimension screenDim = Toolkit.getDefaultToolkit().getScreenSize();
		this.setLocation( screenDim.width / 2 - this.getWidth() / 2,
				screenDim.height / 2 - this.getHeight() / 2);
	}

	/**
	 * Try to login the user and retrieves the server response
	 * @return
	 */
	protected AwxLoginUserResponse login() {
		AwxDefaultLoginService loginInterface = (AwxDefaultLoginService)AwxRpc.getInstance().getServer( DEFAULT_LOGIN_SERVER );
		AwxLoginUserResponse response = loginInterface.tryLoginUser( this.loginUser );
		if( response.isAnswer() ) {
			this.menuConfiguration = response.getMenuConfiguration();
			this.application.setMenuConfiguration( this.menuConfiguration );
			this.application.goToMainMenu();
		}
		return response;
	}



	@Override
	public void setVisible( boolean flag ) {
		if( flag ) {
			this.onBeforeShow();
			this.centerWindow();
			super.setVisible( true );
			this.onShow();
		}
	}

	/**
	 * Called before the window is set visible
	 */
	private void onBeforeShow() {
	}

	/**
	 * Called inmediatly after the window become visible
	 */
	private void onShow() {
	}

	/**
	 * User object for logging
	 * @return loginUser
	 */
	public AwxLoginUser getLoginUser() {
		return loginUser;
	}

	/**
	 * Menu configuration for a logged user
	 * @return menuConfiguration
	 */
	public AwxMenuConfiguration getMenuConfiguration() {
		return menuConfiguration;
	}


	protected AwxApplication getApplication() {
		return application;
	}

	public void setApplication(AwxApplication application) {
		this.application = application;
	}



}
